<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button
          class="button"
          type="primary"
          :icon="Plus"
          @click="showDialogByAdd"
          >添加</el-button
        >
      </div>
    </template>
    <el-table :data="trademarkList" border style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="180" />
      <el-table-column prop="tmName" label="品牌" width="180" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="showDialogById(row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="deleteTrademarkInfo(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="page"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 10]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, jumper,->,sizes,total "
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog
    v-model="dialogFormVisible"
    :title="`${form.id ? '修改' : '添加'}品牌`"
  >
    <el-form :model="form" ref="ruleFormRef" :rules="rules">
      <el-form-item label="商品名字" label-width="90px" prop="tmName">
        <el-input autocomplete="off" v-model="form.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="90px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="`${BASE_URL}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png 文件，且不超过2M大小
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
export default {
  name: "trademark",
};
</script>
<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqGetAllTrademarkListData,
  reqSaveTrademarkInfo,
  reqDeleteTrademarkInfoData,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark";
import type {
  TrademarkListModel,
  TrademarkModel,
} from "@/api/product/model/trademark";
import { onMounted, reactive, ref } from "@vue/runtime-core";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
// 表单校验
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();

const trademarkList = ref<TrademarkListModel>([]);
let page = ref(1); //当前页
let limit = ref(5); // 每页显示最多的数量
// pagination 的必须项
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const loading = ref(true);
const dialogFormVisible = ref(false);
const initTrademark = () => ({ tmName: "", logoUrl: "" });
// 给图片地址设置基础的Url
const BASE_URL = import.meta.env.VITE_API_URL;
// 定义内容总条数
const total = ref(0);
// 定义图片地址
const imageUrl = ref("");
// 收集表单的数据，并加类型限制
let form = reactive<TrademarkModel>(initTrademark());
// 疯转求情数据的接口，在改变页码和初始化时使用
const getTrademarkListData = async (page: number, limit: number) => {
  const result = await reqGetAllTrademarkListData(page, limit);
  total.value = result.total;
  trademarkList.value = result.records;
  // 清除之前的图片校验规则
  ruleFormRef.value?.clearValidate(["logoUrl"]);
};
// 添加商品成功的回调（可以在里边给页面的重新填充图片）
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  form.logoUrl = response.data;
};
// 上传之前的回调（在其中验证图片的格式和大小）
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgTypes = ["image/jpeg", "image/jpg", "image/png"];
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("Avatar picture size can not exceed 5MB!");
    return false;
  }
  return true;
};
// 点击改变当前页码并跳转
const handleSizeChange = (val: number) => {
  getTrademarkListData(1, val);
};
// 点击改变单页显示的条数
const handleCurrentChange = (val: number) => {
  getTrademarkListData(val, 5);
};
// 打开对话框添加数据
const showDialogByAdd = () => {
  // 添加品牌时，先将原来的数据清空
  Object.assign(form, initTrademark());
  delete form.id;
  dialogFormVisible.value = true;
  // 清除之前的校验规则  不写参数的时候，是清空所有的校验规则
  ruleFormRef.value?.clearValidate();
};
// 编辑按钮打开对话框
const showDialogById = (row: TrademarkModel) => {
  (dialogFormVisible.value = true), Object.assign(form, row);
};
// 对话框的添加事件
// const btnTrademark = async () => {
//   if (form.id) {
//     // 更新
//     await reqUpdateTrademarkInfo(form);
//   } else {
//     // 添加
//     await reqSaveTrademarkInfo(form);
//   }
//   // 提示添加成功
//   ElMessage({
//     type: "success",
//     message: "添加品牌成功...",
//   });
//   // 关闭对话框
//   dialogFormVisible.value = false;
//   // 跳转到第1页
//   page.value = 1;
//   getTrademarkListData(page.value, 5);
// };
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (form.id) {
        // 更新
        await reqUpdateTrademarkInfo(form);
        // 提示添加成功
        ElMessage({
          type: "success",
          message: "更新品牌成功...",
        });
      } else {
        // 添加
        await reqSaveTrademarkInfo(form);
        // 提示添加成功
        ElMessage({
          type: "success",
          message: "添加品牌成功...",
        });
        // 关闭对话框
        // 跳转到第1页
        page.value = 1;
      }
      dialogFormVisible.value = false;
      getTrademarkListData(page.value, 5);
    }else{
      console.log('error submit!', fields);
    }
  });
};
// 根据ID删除一条内容
const deleteTrademarkInfo = (row: TrademarkModel) => {
  ElMessageBox.confirm("您真的要删除此条品牌数据吗?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademarkInfoData(row.id as number);
      ElMessage({
        type: "success",
        message: "删除品牌成功",
      });
      page.value = trademarkList.value.length > 1 ? page.value : page.value - 1;
      getTrademarkListData(page.value, 5);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};
// 初始时获取第一页的数据
onMounted(() => {
  getTrademarkListData(1, 5);
});

const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
    { min: 2, max: 8, message: "名称长度在2--8个字符之间", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "请上传一张品牌图片",
      trigger: "change",
    },
  ],
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
